<template>
  <div ref="chart" class="chart-render-box"></div>
</template>
<script setup>
import * as echarts from 'echarts'
import { cloneDeep } from 'lodash'
import { onMounted, ref, reactive, onBeforeUnmount, watch } from 'vue'
let myChart = null
const emits = defineEmits(['quCurrentClick'])
const props = defineProps({
  xData: {
    type: Array,
    default: () => [],
  },
  sData: {
    type: Array,
    default: () => [],
  },
  data1: {
    type: Array,
    default: () => [],
  },
  data2: {
    type: Array,
    default: () => [],
  },
  limit: {
    type: Array,
    default: () => [0, 6],
  },
  isLoop: {
    type: Boolean,
    default: true,
  },
  legendText: {
    type: Array,
    default: () => ['电动自行车总数', '自查清理数量'],
  },
  grid: {
    type: Object,
    default: () => ({
      top: '23%',
      right: '1%',
      left: '10%',
      bottom: '20%',
    }),
  },
})
const propsCopy = reactive({
  // data1: cloneDeep(props.data1),
  data2: cloneDeep(props.data2),
  xData: cloneDeep(props.xData),
})
const [startValue, endValue] = props.limit
const option = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    formatter: function (params) {
      // 初始化tooltip文本
      let tooltipText = params[0].name + '<br/>'

      // 遍历params数组，为每个系列（柱子）添加信息
      params.forEach(function (item, index) {
        // 根据索引或系列名称确定单位
        let unit = ''
        if (index === 0) {
          // 假设第一个柱子使用“栋”作为单位
          unit = '辆'

        } else if (index === 1) {
          // 假设第二个柱子使用“个”作为单位
          unit = '栋'
        }
        tooltipText +=
          item.marker + item.seriesName + ': ' + item.value + unit + '<br/>'
      })

      return tooltipText
    },
  },
  legend: {
    // itemGap: 50,
    top: '0%',
    data: [...props.legendText],
    // data: ['电动自行车总数', '核查清理数量'],
    textStyle: {
      color: '#f9f9f9',
      borderColor: '#fff',
    },
  },
  grid: props.grid,
  // 控制显示几个柱子
  dataZoom: {
    show: false,
    startValue,
    endValue,
  },
  // dataZoom: {
  //     type: 'inside',
  //     maxValueSpan: 14
  // },
  xAxis: [
    {
      type: 'category',
      data: props.xData,
      axisLine: {
        lineStyle: {
          color: '#02387B',
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        margin: 10,
        color: 'rgba(255,255,255,1)',
        textStyle: {
          fontSize: 12,
        },
        formatter: function (e) {
          //   console.log('@e===', e)
          //   let str = ''
          //   let arr = e.split('')
          //   for (let i = 0; i < arr.length; i++) {
          //     str += arr[i] + '\n'
          //   }
          return e
        },
      },
    },
  ],
  yAxis: [
    {
      name: '辆',
      nameTextStyle: {
        align: 'right',
      },
      axisLabel: {
        formatter: '{value}',
        color: 'rgba(255,255,255,0.52)',
      },
      axisLine: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(108, 128, 151, 0.3)',
        },
      },
    },
  ],
  series: [
    // {
    //   name: `${props.legendText[0]}`,
    //   // name: `电动自行车总数`,
    //   type: 'bar',
    //   barWidth: 15,
    //   label: {
    //     normal: {
    //       position: 'top',
    //       color: '#fff',
    //       show: true,
    //       formatter: function (params) {
    //         // 在这里添加百分号并返回格式化后的标签内容
    //         return params.value
    //       },
    //     },
    //   },
    //   itemStyle: {
    //     normal: {
    //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    //         {
    //           offset: 0,
    //           color: '#15E0FF',
    //         },
    //         {
    //           offset: 1,
    //           color: '#159AFF',
    //         },
    //       ]),
    //     },
    //   },
    //   data: props.data1,
    //   yAxisIndex: 0,
    // },
    {
      name: `${props.legendText[0]}`,
      // name: `核查清理数量`,
      type: 'bar',
      barWidth: 15,
      label: {
        normal: {
          position: 'top',
          color: '#fff',
          show: true,
          formatter: function (params) {
            // 在这里添加百分号并返回格式化后的标签内容
            return params.value + '辆'
          },
        },
      },
      itemStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: '#15FFC5',
            },
            {
              offset: 1,
              color: '#15F7FF',
            },
          ]),
        },
      },
      data: props.data2,
      yAxisIndex: 0,
    },
  ],
})
function _clearInterval(timeId) {
  timeId && window.clearInterval(timeId)
}
const resizeHandler = () => {
  myChart.resize()
}
const chart = ref()
const timer1 = ref(null)
const initCharts = () => {
  chart.value.removeAttribute('_echarts_instance_')
  myChart = echarts.init(chart.value)
  myChart.setOption(option.value)
  window.addEventListener('resize', resizeHandler)
  myChart.on('click', handleClick)
  if (props.isLoop) {
    timer1.value = setInterval(() => {
      // 进行操作（深拷贝）
      // const item1 = propsCopy.data1.shift()
      // propsCopy.data1.push(item1)
      const item2 = propsCopy.data2.shift()
      propsCopy.data2.push(item2)
      const item3 = propsCopy.xData.shift()
      propsCopy.xData.push(item3)
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          show: true,
        },
        series: [
          // {
          //   data: propsCopy.data1,
          //   type: 'bar',
          // },
          {
            data: propsCopy.data2,
            type: 'bar',
          },
        ],
        xAxis: {
          type: 'category',
          data: propsCopy.xData,
        },
      })
    }, 5000)
  }
}
const handleClick = (params) => {
  console.log('点击柱状图====', params)
  // 发送自定义事件通知父组件
  emits('quCurrentClick', params)
}
watch(
  () => props,
  (newValue, oldValue) => {
    // propsCopy.data1 = cloneDeep(newValue.data1)
    propsCopy.data2 = cloneDeep(newValue.data2)
    propsCopy.xData = cloneDeep(newValue.xData)
    if (props.isLoop) {
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          show: true,
        },
        xAxis: {
          data: propsCopy.xData,
          type: 'category',
        },
        series: [
          // {
          //   data: propsCopy.data1,
          //   type: 'bar',
          // },
          {
            data: propsCopy.data2,
            type: 'bar',
          },
        ],
      })
    }
  },
  { deep: true }
)
onMounted(() => {
  initCharts()
})
onBeforeUnmount(() => {
  if (props.isLoop) {
    _clearInterval(timer1.value)
  }
  window.removeEventListener('resize', resizeHandler)
})
defineExpose({
  initCharts,
  props,
})
</script>
<style scoped lang="scss">
.chart-render-box {
  width: 100%;
  height: 100%;
  flex: 1;
}
</style>
